import { _decorator, Component, Node, Sprite, SpriteFrame, Texture2D } from "cc";
import { Engine } from "../Engine";
import { i18n, LanguageEvent } from "../manager/LanguageManager";
import Logger from "../utils/Logger";
const { ccclass, property } = _decorator;

@ccclass("LocalizedSprite")
export class LocalizedSprite extends Component {
    sprite: Sprite | null = null;

    @property({
        tooltip: "资源路径（i18n/textures/内的相对路径）",
    })
    public path: string = "";

    onLoad() {
        Engine.eventManager.on(LanguageEvent.CHANGE, this.updateSprite, this);
        this.updateSprite();
    }

    onDestroy() {
        Engine.eventManager.off(LanguageEvent.CHANGE, this);
    }

    async updateSprite() {
        if (!i18n.currentLanguage) {
            return;
        }
        const sprComp: Sprite = this.getComponent(Sprite)!;
        // 获取语言标记
        const path = `i18n/textures/${i18n.currentLanguage}/${this.path}/spriteFrame`;
        Logger.log("path:" + path);

        const spritFrame = await Engine.resManager.loadPath<SpriteFrame>(path);
        if (!spritFrame) {
            Logger.error("[LanguageSprite] 资源不存在 " + path);
        }
        console.log(spritFrame);
        sprComp.spriteFrame = spritFrame;
    }
}
